package com.ghsc.yigou.live.utils;

import android.annotation.SuppressLint;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 项目：GuoHuaMall
 * 包名：com.ghsc.ghxc.utils
 * 类名：SmsContentUtil
 * 创建时间：2023/8/21 22:28
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
public class SmsContentUtil  extends ContentObserver {

    public static final String SMS_URI_INBOX = "content://sms/inbox";

    private AppCompatActivity activity = null;

    private String smsContent = "";

    private EditText verifyText = null;

    public SmsContentUtil(Handler handler) {
        super(handler);
    }

    public SmsContentUtil(AppCompatActivity activity, Handler handler, EditText verifyText) {
        super(handler);
        this.activity = activity;
        this.verifyText = verifyText;
    }
    @SuppressLint("Range")
    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Cursor cursor = null;// 光标
        // 读取收件箱中指定号码的短信
        cursor = activity.getContentResolver().query(Uri.parse(SMS_URI_INBOX), new String[] {
                        "_id", "address", "body", "read", "date" }, "address=? and read=?",
                new String[] { "15803411546", "0" }, "date desc");

        if (cursor != null) {// 如果短信为未读模式
            cursor.moveToFirst();
            if (cursor.moveToFirst()) {

                String smsbody = cursor.getString(cursor.getColumnIndex("body"));
                Log.e("自动获取", "onChange: "+smsbody );
                String regEx = "[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(smsbody.toString());
                smsContent = m.replaceAll("").trim().toString();
                verifyText.setText(smsContent);
                verifyText.setSelection(verifyText.getText().toString().trim().length());
            }

        }
    }

}
